<template>
	<view class="root f1 oh safe-area-inset-bottom">
		<label
			:style="{ margin: `30rpx 20rpx`, padding: `0 20rpx` }"
			class="height-70 bgc-f0f0f0 br-34"
		>
			<uni-icons type="search" color="#ccc" />
			<input
				class="ml-12 f1 fs-28"
				type="text"
				placeholder="搜索商品"
				placeholder-style="color: #ccc"
				v-model="keywords"
				confirm-type="search"
				@confirm="search"
			/>
		</label>
		<view class="f1 oh fd-row">
			<scroll-view :show-scrollbar="false" scroll-y>
				<view
					class="category"
					@click="openInputCategoryPopup"
					hover-class="tap-hover"
					hover-stay-time="90"
				>
					<uni-icons type="plus" color="#333" />
					<text>添加分类</text>
				</view>
				<view
					v-for="(category, index) in categories"
					:key="index"
					:class="[{ active: categoryId === category.id }, 'category']"
					@click="chooseCategory(category.id)"
					@longpress="setCategory(index)"
				>
					<text>{{ category.name }}</text>
				</view>
			</scroll-view>

			<scroll-view @scrolltolower="getListData" scroll-y class="f1 oh bgc-fff">
				<label class="height-30" />
				<uni-swipe-action>
					<block v-for="(commodity, index) in commodities.list" :key="index">
						<uni-swipe-action-item
							:right-options="options"
							@click="operation($event, index)"
						>
							<view class="fd-row ml-30 mr-30 bgc-fff">
								<image
									class="br-8"
									:style="{ width: `170rpx`, height: `170rpx` }"
									:src="commodity.cover_image"
									mode="aspectFill"
								/>
								<view class="f1 oh ml-18 jc-sa">
									<text class="color-333 fs-30 fw-600 ellipsis">
										{{ commodity.name }}
									</text>
									<text class="color-999 fs-24 multi-ellipsis">
										{{ commodity.des }}
									</text>
									<text class="color-ef1b1b fs-32 fw-600 as-end">
										￥{{ Number(commodity.price).toFixed(2) }}
									</text>
								</view>
							</view>
						</uni-swipe-action-item>
						<label class="height-30" />
					</block>
				</uni-swipe-action>
				<uni-load-more :status="loadStatus" />
			</scroll-view>
		</view>

		<uni-popup ref="inputCategory">
			<view class="bgc-fff br-20" :style="{ padding: `30rpx` }">
				<text class="color-f45455 fs-24 text-center">
					*长按分类名称可对所选分类进行编辑*
				</text>

				<input
					class="input mt-30 fs-30 text-center"
					type="text"
					maxlength="6"
					:focus="true"
					v-model="categoryName"
					placeholder="输入分类名称"
					placeholder-style="color: #ccc"
				/>
				<button
					:disabled="!categoryName"
					@click="editCategory"
					:style="{
						margin: `30rpx 24rpx 0`,
						backgroundImage: `linear-gradient(to right, #f45455, #ff7b6f)`,
					}"
					class="lh-2 color-fff fs-30"
				>
					提交
				</button>
			</view>
		</uni-popup>
	</view>
</template>

<script lang="ts">
	import { Vue, Component } from "vue-property-decorator";
	import { Pager } from "@/static/type";

	let requestFlag: boolean = false;
	@Component
	export default class GetCommodity extends Vue {
		// component property
		categories: AnyObject[] = [];
		categoryId: number = 0;
		categoryIndex: number = -1;

		commodities: Pager<AnyObject> = { page: 1, list: [], size: 18 };
		loadStatus: string = "loading";
		keywords: string = "";
		categoryName: string = "";
		options: AnyObject[] = [
			{
				text: "编辑",
				style: {
					backgroundColor: "#007aff",
				},
			},
			{
				text: "删除",
				style: {
					backgroundColor: "#dd524d",
				},
			},
		];

		onShow() {
			if (!this.categoryId) return;
			this.keywords = "";
			this.search();
		}
		onLoad() {
			this.$request.get("/shop/cateList").then(({ data }) => {
				this.categories = data;
				this.categoryId = data[0]?.id || 0;
				this.keywords = "";
				this.search();
			});
		}

		chooseCategory(id: number) {
			if (requestFlag || this.categoryId === id) return;
			this.categoryId = id;
			this.keywords = "";
			this.search();
		}

		search() {
			this.commodities.list = [];
			this.commodities.page = 1;
			this.getListData();
		}

		getListData() {
			const { $request, commodities, categoryId: cate_id, keywords } = this;

			if (requestFlag || !commodities.page) return;
			(requestFlag = true), (this.loadStatus = "loading");

			$request
				.get("/shop/productList", {
					page: commodities.page,
					size: commodities.size,
					cate_id,
					keywords,
				})
				.then(({ data }) => {
					commodities.list.push(...data.data);
					commodities.page = data.current_page < data.last_page ? ++data.current_page : 0;
					this.loadStatus = commodities.page ? "more" : "noMore";
				})
				.finally(() => (requestFlag = false));
		}

		operation(e: AnyObject, index: number) {
			const { id } = this.commodities.list[index];

			if (!e.index) {
				uni.navigateTo({
					url: `/pages/businessBackground/SetCommodity?category_id=${this.categoryId}&commodity_id=${id}`,
				});
				return;
			}
			uni.showToast({ title: "Loading", icon: "loading" });
			this.$request.get("/shop/delProduct", { id }).then(({ msg: title }) => {
				this.commodities.list.splice(index, 1);
				uni.showToast({ title });
			});
		}

		openInputCategoryPopup() {
			this.categoryIndex = -1;
			(<AnyObject>this.$refs.inputCategory).open();
		}

		editCategory() {
			uni.showLoading({ title: "Loading..." });
			const { $request, $refs, categories, categoryName, categoryIndex } = this;
			const category = categories[categoryIndex];
			$request
				.get("/shop/editCate", {
					name: categoryName,
					id: category?.id,
				})
				.then(({ data }) => {
					!category?.id
						? categories.unshift({ id: +data, name: categoryName })
						: (category.name = categoryName);

					this.categoryName = "";
					(<AnyObject>$refs.inputCategory).close();
					uni.hideLoading();
				});
		}
		async setCategory(index: number) {
			const [actionSheetFail, actionSheetRes]: any = await uni.showActionSheet({
				itemList: ["添加商品", "修改名称", "删除分类"],
				itemColor: "#fb8629",
			});

			if (actionSheetFail) return;

			const { id, name } = this.categories[index];

			switch (actionSheetRes.tapIndex) {
				case 0:
					uni.navigateTo({
						url: `/pages/businessBackground/SetCommodity?category_id=${id}`,
					});
					break;
				case 1:
					this.categoryName = name;
					this.categoryIndex = index;
					(<AnyObject>this.$refs.inputCategory).open();
					break;
				case 2:
					uni.showLoading({ title: "Loading..." });
					const { data } = await this.$request.get("/shop/productList", {
						page: 1,
						size: 1,
						cate_id: id,
						keywords: "",
					});
					uni.hideLoading();
					if (data.data.length) {
						const [modalFail, modalRes]: any = await uni.showModal({
							title: "警告",
							content: "该分类存在所属商品，继续删除将清空该分类，确定要继续吗？",
							cancelColor: "#f50",
						});

						if (modalFail || modalRes.cancel) return;
					}
					uni.showLoading({ title: "Loading..." });
					this.$request.get("/shop/delCate", { id }).then(({ msg: title }) => {
						this.categories.splice(index, 1);
						uni.showToast({ title });
					});
					break;
				default:
					break;
			}
		}
	}
</script>

<style lang="scss" scoped>
	// scss
	button[disabled] {
		color: #fff;
	}
	.category {
		flex-direction: row;
		align-items: center;
		justify-content: center;
		width: 200rpx;
		line-height: 90rpx;
		font-size: 26rpx;
		color: #666;
		&.active {
			background-color: #fff;
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
		}
		text {
			@extend .ellipsis;
			margin: 0 6rpx;
		}
	}
</style>